<template>
    <t-drawer
            :visible="visible"
            :fullscreen="true"
            :switchFullscreen="true"
            :confirmLoading="loading"
            @close="() => {$emit('cancel');}"
            class="t-dr"
            :closable="false"
    >
        <a-spin :spinning="loading">
            <div class="flex design-header">
                <div class="logo">
                    <img src="https://zysd-shanghai.oss-cn-shanghai.aliyuncs.com/emis/logo.png" alt="logo">
                    <div class="title">新增</div>
                </div>
                <div class="left-step" :style="leftStep">
                    <!-- <a-steps v-model="currentIndex" @change="setDataSource" size="default"> -->
                    <a-steps :current="currentIndex" size="default">
                        <a-step :title="item.name" v-for="(item, index) in stepList" :key="index"/>
                    </a-steps>
                </div>
                <div class="right-btn">
                    <a-button :class="[currentIndex == 0 ? 'buttonGray' : 'margin-right-xs']" icon="left"
                              @click="changeCurrentIndex('left')" :disabled="currentIndex == 0">上一步
                    </a-button>
                    <a-button :class="[
              currentIndex == stepList.length - 1
                ? 'buttonGray'
                : 'margin-right-xs',
            ]" icon="right" @click="changeCurrentIndex('right')" :disabled="currentIndex == stepList.length - 1">下一步
                    </a-button>
                    <a-button :class="[
              currentIndex != stepList.length - 1
                ? 'buttonGray'
                : 'cu-btn-primary',
            ]" :disabled="currentIndex != stepList.length - 1" icon="check" @click="handleSubmitData"
                              :loading="loading">保存
                    </a-button>
                    <a-button class="cancelBtn" icon="close" @click="handleClose">关闭</a-button>
                </div>
            </div>
            <div class="padding design-body">
                <a-form :form="form" v-show="currentIndex === 0">
                    <a-row>
                        <a-col :lg="{ span: 24 }">
                            <a-form-item
                                    label="主键"
                                    :label-col="labelCol"
                                    :wrapper-col="wrapperCol"
                            >
                                <a-input
                                        v-decorator="['primaryKeyPolicy', { initialValue: 'uuid' }]"
                                        placeholder="主键策略"
                                        readOnly
                                />
                            </a-form-item>
                        </a-col>
                        <a-col :lg="{ span: 24 }">
                            <a-form-item
                                    label="类名"
                                    :label-col="labelCol"
                                    :wrapper-col="wrapperCol"
                            >
                                <a-input v-decorator="['className']" placeholder="类名"/>
                            </a-form-item>
                            <a-form-item class="hiddenItem">
                                <a-input v-decorator="['uuid']" type="hidden"/>
                            </a-form-item>
                        </a-col>
                        <a-col :lg="{ span: 24 }">
                            <a-form-item
                                    label="表单风格"
                                    :label-col="labelCol"
                                    :wrapper-col="wrapperCol"
                            >
                                <a-select
                                        v-decorator="['formStyle', { initialValue: '24' }]"
                                        placeholder="表单风格"
                                >
                                    <a-select-option
                                            v-for="(item, index) in formTypeList"
                                            :key="index"
                                            :value="item.value"
                                    >
                                        {{ item.text }}
                                    </a-select-option>
                                </a-select>
                            </a-form-item>
                        </a-col>
                        <a-col :lg="{ span: 24 }">
                            <a-form-item
                                    label="滚动条"
                                    :label-col="labelCol"
                                    :wrapper-col="wrapperCol"
                            >
                                <a-select
                                        v-decorator="['scrollBar', { initialValue: '0' }]"
                                        placeholder="滚动条"
                                >
                                    <a-select-option value="1"> 有</a-select-option>
                                    <a-select-option value="0"> 无</a-select-option>
                                </a-select>
                            </a-form-item>
                        </a-col>
                        <a-col :lg="{ span: 24 }">
                            <a-form-item
                                    label="复选框"
                                    :label-col="labelCol"
                                    :wrapper-col="wrapperCol"
                            >
                                <a-select
                                        v-decorator="['checkBox', { initialValue: '1' }]"
                                        placeholder="复选框"
                                >
                                    <a-select-option value="1"> 有</a-select-option>
                                    <a-select-option value="0"> 无</a-select-option>
                                </a-select>
                            </a-form-item>
                        </a-col>
                    </a-row>
                </a-form>
                <dataSet ref="dataSet" :isEdit="isEdit" v-show="currentIndex === 1"></dataSet>
                <div v-show="currentIndex === 2">
                    <a-table size="small" :columns="columns" :data-source="dataSource" :pagination="false">
                        <span slot="whetherNull" slot-scope="text,record">
                             <a-tag :color="text == 'true'  ? 'green' : 'red'">
                                 {{  text == "true" ? "是" : "否" }}
                             </a-tag>
                        </span>
                        <span slot="primaryKey" slot-scope="text,record">
                             <a-tag :color="text == 'true'  ? 'green' : 'red'">
                                 {{  text == "true" ? "是" : "否" }}
                             </a-tag>
                        </span>
                        <template slot="action" slot-scope="text, record, index">
                            <a @click="() => handleEdit(record,index,'visible1','mdl1')">编辑</a>
                        </template>
                    </a-table>
                </div>
                <div v-show="currentIndex === 3">
                    <!--<a-button type="primary" icon="plus">新增</a-button>-->
                    <a-table size="small" :columns="columns2" :data-source="dataSource" :pagination="false">
                        <template slot="action" slot-scope="text, record, index">
                            <a @click="() => handleEdit(record,index,'visible2','mdl2')">编辑</a>
                        </template>
                    </a-table>
                </div>
                <div v-show="currentIndex === 4">
                    <!--<a-button type="primary" icon="plus">新增</a-button>-->
                    <a-table size="small" :columns="columns3" :data-source="dataSource" :pagination="false">
                        <span slot="listDisplay" slot-scope="text">
                             <a-tag :color="text == 'true'  ? 'green' : 'red'">
                                 {{  text == "true" ? "是" : "否" }}
                             </a-tag>
                        </span>
                        <span slot="listWhetherSort" slot-scope="text">
                             <a-tag :color="text == 'true'  ? 'green' : 'red'">
                                 {{  text == "true" ? "是" : "否" }}
                             </a-tag>
                        </span>
                        <span slot="whetherReadOnly" slot-scope="text">
                             <a-tag :color="text == 'true'  ? 'green' : 'red'">
                                 {{  text == "true" ? "是" : "否" }}
                             </a-tag>
                        </span>
                        <span slot="whetherRequired" slot-scope="text">
                             <a-tag :color="text == 'true'  ? 'green' : 'red'">
                                 {{  text == "true" ? "是" : "否" }}
                             </a-tag>
                        </span>
                        <span slot="whetherSearch" slot-scope="text">
                             <a-tag :color="text == 'true'  ? 'green' : 'red'">
                                 {{  text == "true" ? "是" : "否" }}
                             </a-tag>
                        </span>
                        <template slot="action" slot-scope="text, record, index">
                            <a @click="() => handleEdit(record,index,'visible3','mdl3')">编辑</a>
                        </template>
                    </a-table>
                </div>
                <div v-show="currentIndex === 5">
                    <!--<a-button type="primary" icon="plus">新增</a-button>-->
                    <a-table size="small" :columns="columns4" :data-source="dataSource" :pagination="false">
                        <template slot="action" slot-scope="text, record, index">
                            <a @click="() => handleEdit(record,index,'visible4','mdl4')">编辑</a>
                        </template>
                    </a-table>
                </div>
            </div>
        </a-spin>
        <!--四张表的弹窗-->
        <edit-form-one ref="createModal1" :visible="visible1" :model="mdl1"
                        @cancel="()=>{mdl1=null;visible1=false}" @ok="handleOk('createModal1','visible1')"/>

        <edit-form-two ref="createModal2" :visible="visible2" :model="mdl2"
                       @cancel="()=>{mdl2=null;visible2=false}" @ok="handleOk('createModal2','visible2')"/>

        <edit-form-three ref="createModal3" :visible="visible3" :model="mdl3"
                       @cancel="()=>{mdl3=null;visible3=false}" @ok="handleOk('createModal3','visible3')"/>

        <edit-form-four ref="createModal4" :visible="visible4" :model="mdl4"
                   @cancel="()=>{mdl4=null;visible4=false}" @ok="handleOk('createModal4','visible4')"/>
    </t-drawer>
</template>

<script>
    import dataSet from "./dataSet";
    import editFormOne from "./editTable1";
    import editFormTwo from "./editTable2";
    import editFormThree from "./editTable3";
    import editFormFour from "./editTable4";

    import pick from "lodash.pick";
    // 表单字段
    const fields = [
        "uuid",
        "database",
        "tableType",
        "tableName",
        "notes",
        "primaryKeyPolicy",
        "className",
        "scrollBar",
        "checkBox",
        "formStyle",
    ];
    import TDictSelectTag from "@/components/TopVUI/dict/TDictSelectTag";
    import {mergeArry} from "@/utils/util";
    import {camelCase} from "@/utils/index";
    import {
        FormTypes,
        validateFormAndTables,
        getRefPromise,
        VALIDATE_NO_PASSED,
    } from "@/utils/TEditableTableUtil";
    import TEditableTable from "./genTable";

    export default {
        props: {
            visible: {
                type: Boolean,
                required: true,
            },
            loading: {
                type: Boolean,
                default: () => false,
            },
            model: {
                type: Object,
                default: () => null,
            },
            isEdit: {
                type: Boolean,
                default: () => false
            }
        },
        components: {
            TDictSelectTag,
            TEditableTable,
            dataSet,
            editFormOne,
            editFormTwo,
            editFormThree,
            editFormFour,
        },
        data() {
            return {
                currentIndex: 0,
                stepList: [
                    {
                        name: "基本配置",
                        key: 0,
                    },
                    {
                        name: "选择数据库表",
                        key: 1,
                    },
                    {
                        name: "数据库属性",
                        key: 2,
                    },
                    {
                        name: "java实体类",
                        key: 3,
                    },
                    {
                        name: "页面属性",
                        key: 4,
                    },
                    {
                        name: "校验字段",
                        key: 5,
                    }
                ],
                title: "",
                labelCol: {
                    xs: {
                        span: 24,
                    },
                    sm: {
                        span: 5,
                    },
                },
                wrapperCol: {
                    xs: {
                        span: 24,
                    },
                    sm: {
                        span: 16,
                    },
                },
                form: this.$form.createForm(this),
                codeBaseList: [],
                currentIndex: 1,
                url: {
                    generateCodeMoreSave: "/system/sysGenTable/generateCodeMoreSave",
                    getAllDatabases: "/system/sysGenTable/getAllDatabases",
                    getByPuuid: "/system/sysGenFiled/getByPuuid",
                    getValueType: "/system/sysSample/getValueType",
                    formWizardAddSave: "/system/sysGenTable/formWizardAddSave",
                    formWizardsUpdate: "/system/sysGenTable/formWizardsUpdate",
                    deleteByUuid: "/system/generator/deleteByUuid", //uuid
                    getPageSetByDatabaseAll: "/system/sysGenTable/getPageSetByDatabaseAll",
                },
                dataSource1: [],
                dataSource2: [],
                dataSource3: [],
                dataSource: [],
                tableTypeList: [
                    {text: "数据表格", value: "数据表格"},
                    {text: "可编辑表格", value: "可编辑表格"},
                    {text: "树形表格", value: "树形表格"},
                ],
                formTypeList: [
                    {text: "一列", value: "24"},
                    {text: "二列", value: "12"},
                    {text: "三列", value: "8"},
                    {text: "四列", value: "6"},
                ],
                type: true,
                columns: [
                    {
                        title: "字段名称",
                        key: "listClearly",
                        dataIndex: 'listClearly',
                    },
                    {
                        title: "注释",
                        key: "explain",
                        dataIndex: 'explain',
                    },
                    {
                        title: "字段类型",
                        key: "fieldType",
                        dataIndex: 'fieldType',
                    },
                    {
                        title: "长度",
                        key: "listClearlyLength",
                        dataIndex: 'listClearlyLength',
                    },
                    {
                        title: "默认值",
                        key: "fieldDefaultvalue",
                        dataIndex: 'fieldDefaultvalue',
                    },
                    {
                        title: "小数点",
                        key: "decimalPoint",
                        dataIndex: 'decimalPoint',
                    },
                    {
                        title: "允许空值",
                        key: "whetherNull",
                        dataIndex: 'whetherNull',
                        scopedSlots: {
                            customRender: "whetherNull"
                        },
                        align:'center'
                    },
                    {
                        title: "主键",
                        key: "primaryKey",
                        dataIndex: 'primaryKey',
                        scopedSlots: {
                            customRender: "primaryKey"
                        },
                        align:'center'
                    },
                    {
                        title: "操作",
                        // dataIndex: "action",
                        scopedSlots: {
                            customRender: "action"
                        },
                        align:'center'
                    },
                ],
                columns2: [
                    {
                        title: "列名",
                        key: "listClearly",
                        dataIndex: 'listClearly',
                    },
                    {
                        title: "说明",
                        key: "explain",
                        dataIndex: 'explain',
                    },
                    {
                        title: "java类型",
                        key: "javaType",
                        dataIndex: 'javaType',
                    },
                    {
                        title: "java属性名称",
                        key: "javaFiled",
                        dataIndex: 'javaFiled',
                    },
                    {
                        title: "操作",
                        dataIndex: "action",
                        scopedSlots: {
                            customRender: "action"
                        },
                        align:'center',
                    },
                ],
                columns3: [
                    {
                        title: "字段名称",
                        key: "listClearly",
                        dataIndex: 'listClearly',
                    },
                    {
                        title: "注释",
                        key: "explain",
                        dataIndex: 'explain',
                    },
                    {
                        title: "控件类型",
                        key: "controlType",
                        dataIndex: 'controlType',
                    },
                    {
                        title: "控件长度",
                        key: "controlLength",
                        dataIndex: 'controlLength',
                    },
                    {
                        title: "控件默认值",
                        key: "controlDefaultvalue",
                        dataIndex: 'controlDefaultvalue',
                    },
                    {
                        title: "表单排序",
                        key: "formSort",
                        dataIndex: 'formSort',
                    },
                    {
                        title: "列表显示",
                        key: "listDisplay",
                        dataIndex: 'listDisplay',
                        scopedSlots: {
                            customRender: "listDisplay"
                        },
                        align:'center'
                    },
                    {
                        title: "列表是否排序",
                        key: "listWhetherSort",
                        dataIndex: 'listWhetherSort',
                        scopedSlots: {
                            customRender: "listWhetherSort"
                        },
                        align:'center'
                    },
                    {
                        title: "是否只读",
                        key: "whetherReadOnly",
                        dataIndex: 'whetherReadOnly',
                        scopedSlots: {
                            customRender: "whetherReadOnly"
                        },
                        align:'center'
                    },
                    {
                        title: "是否查询",
                        key: "whetherSearch",
                        dataIndex: 'whetherSearch',
                        scopedSlots: {
                            customRender: "whetherSearch"
                        },
                        align:'center'
                    },
                    {
                        title: "必填",
                        key: "whetherRequired",
                        dataIndex: 'whetherRequired',
                        scopedSlots: {
                            customRender: "whetherRequired"
                        },
                        align:'center'
                    },
                    {
                        title: "操作",
                        scopedSlots: {
                            customRender: "action"
                        },
                        align:'center'
                    },
                ],
                columns4: [
                    {
                        title: "字段名称",
                        key: "listClearly",
                        dataIndex: 'listClearly',
                    },
                    {
                        title: "注释",
                        key: "explain",
                        dataIndex: 'explain',
                    },
                    {
                        title: "验证规则",
                        key: "validationRules",
                        dataIndex: 'validationRules',
                    },
                    {
                        title: "字典code",
                        key: "dictionariesCode",
                        dataIndex: 'dictionariesCode',
                    },
                    {
                        title: "操作",
                        scopedSlots: {
                            customRender: "action"
                        },
                        align:'center'
                    },
                ],
                dicSetCodeList: [],
                leftStep: {
                    width: 'calc(70% - 160px)',
                    padding: '0 10%'
                },
                visible1:false,
                visible2:false,
                visible3:false,
                visible4:false,
                mdl1:{},
                mdl2:{},
                mdl3:{},
                mdl4:{},
                currentTableIndex:''
            };
        },
        mounted() {
            this.getDicSetCode();
        },
        methods: {
            // 新增
            add(m) {
                this.type = true;
                this.currentIndex = 0;
                this.getAllDatabases();
                this.dataSource1 = [];
                this.dataSource2 = [];
                this.dataSource3 = [];
                this.dataSource = [];
                this.getfeiledList("数据表格");
            },
            added(val) {
                this.setDataSource(val.target.dataSource);
                getRefPromise(this, `tabel${this.currentIndex + 1}`).then((editableTable) => {
                    editableTable.resetScrollTop();
                });
            },
            getDicSetCode() {
                this.$post("/system/dicSet/selectAll", {text: this.codeTxt}).then(
                    (res) => {
                        this.dicSetCodeList = res;
                        this.columns4[3].options = this.dicSetCodeList;
                    }
                );
            },
            deleted(val, a, b) {
                let newData = this.dataSource;
                if (b && b > 0) this.setDataSource(newData.splice(b, 1));
            },
            // 编辑
            edit(m) {
                this.type = false;
                this.currentIndex = 0;
                this.getByPuuid(m.uuid);
            },
            // 获取数据库数据列表
            getAllDatabases() {
                this.$post(this.url.getAllDatabases).then((res) => {
                    this.codeBaseList = res.rows;
                });
            },
            // 编辑获取字段列表
            getByPuuid(uuid) {
                this.$post(this.url.getByPuuid, {
                    uuid: uuid,
                }).then((res) => {
                    this.dataSource1 = res;
                    this.dataSource2 = res;
                    this.dataSource3 = res;
                    this.dataSource = res;

                });
            },
            // 获取字段列表
            getfeiledList(e) {
                this.$post(this.url.getValueType, {value: e}).then((res) => {
                    this.dataSource1 = res;
                    this.dataSource2 = res;
                    this.dataSource3 = res;
                    this.dataSource = res;
                });
            },
            //查询获取数据库
            kumingChange(value) {
                this.codeBaseList = [];
                this.$post(this.url.getAllDatabases, {
                    database: value,
                }).then((res) => {
                    this.codeBaseList = res.row;
                });
            },
            changTabletype(e) {
                if (this.type) this.getfeiledList(e);
            },
            // 字段的新增删除
            changeRows(val) {
                this.dataSource = val;
            },
            changeCurrentIndex(type) {
                if (type == "left") {
                    this.currentIndex -= 1;
                } else {
                    this.currentIndex += 1;
                }
                getRefPromise(this, `tabel${this.currentIndex + 1}`).then((editableTable) => {
                    editableTable.resetScrollTop();
                });
            },
            getAllTable() {
                return Promise.all([
                    getRefPromise(this, "tabel1"),
                    getRefPromise(this, "tabel2"),
                    getRefPromise(this, "tabel3"),
                    getRefPromise(this, "tabel4"),
                ]);
            },
            // 保存数据
            handleSubmit() {
                let that = this;
                that.getAllTable()
                    .then((tables) => {
                        /** 一次性验证主表和所有的次表 */
                        return validateFormAndTables(that.form, tables);
                    })
                    .then((allValues) => {
                        let url = "";
                        that.form.validateFields((errors, values) => {
                            if (!errors) {
                                let params = {
                                    formdata: JSON.stringify(allValues.formValue),
                                    southTab: JSON.stringify(this.dataSource),
                                };
                                if (values.uuid) {
                                    url = that.url.formWizardsUpdate;
                                } else {
                                    url = that.url.formWizardAddSave;
                                }
                                that.$post(url, params).then((res) => {
                                    if (res.statusCode === 200 || res === 1) {
                                        that.$message.success(res.message);
                                        that.$emit("ok");
                                    } else {
                                        that.$emit("ok");
                                        that.$message.info(res.message);
                                    }
                                });
                            } else {
                                console.log("have errors");
                            }
                        });
                    })
                    .catch((e) => {
                        if (e.error === VALIDATE_NO_PASSED) {
                            // 如果有未通过表单验证的子表，就自动跳转到它所在的tab
                            this.currentIndex = e.index == null ? this.currentIndex : e.index;
                            getRefPromise(this, `tabel${this.currentIndex + 1}`).then(
                                (editableTable) => {
                                    editableTable.resetScrollTop();
                                }
                            );
                            this.$message.warn("请完善信息");
                        } else {
                            console.error(e);
                        }
                    });
            },
            //类名转换 驼峰命名
            changeClassName(e) {
                let val = camelCase(e.target.value);
                this.form.setFieldsValue({className: val});
            },
            // 修改
            handleChange(value, key, column, index) {
                const newData = [...this.dataSource];
                const target = newData[index];
                if (target) {
                    target[column] = value;
                    if (column === "listClearly") {
                        target.javaFiled = camelCase(value);
                    }
                    this.setDataSource(newData);
                }
            },
            valueChange(val) {
                this.handleChange(
                    val.value,
                    val.row.listClearly,
                    val.column.key,
                    val.index
                );
            },
            setDataSource(newData) {
                if (this.currentIndex == 2) {
                    this.dataSource = newData;
                    this.dataSource2 = newData;
                    this.dataSource3 = newData;
                } else if (this.currentIndex == 3) {
                    this.dataSource = newData;
                    this.dataSource1 = newData;
                    this.dataSource3 = newData;
                } else if (this.currentIndex == 4) {
                    this.dataSource = newData;
                    this.dataSource1 = newData;
                    this.dataSource2 = newData;
                } else {
                    this.dataSource = newData;
                    this.dataSource1 = newData;
                    this.dataSource2 = newData;
                }
            },
            handleClose() {
                let that = this
                that.$confirm({
                    title: '警告',
                    content: '关闭后所有未保存的数据将会清空，请谨慎操作！',
                    okText: '关闭',
                    okType: 'danger',
                    cancelText: '取消',
                    onOk() {
                        that.$emit('cancel');
                        that.activeKey = '0';
                        // that.$refs.formView.data.list = [];
                        // that.$refs.listPage.data = [];
                        // that.$refs.listPage.selectedRowKeys = [];
                        // that.$refs.formView.selectItem = { key: '' };
                        // that.$refs.formView.options = {};
                    }
                })
            },
            handleSubmitData() {
            },
            handleEdit(record,index,visible,mdl){
                //当前行数
                this.currentTableIndex = index
                this[`${visible}`] = true
                this[`${mdl}`] = {...this.dataSource[index]}
            },
            handleOk(){
                this.dataSource
                this.visible4 = false
            },
            handleOk(ref,visible) {
                const form = this.$refs[`${ref}`].form
                //表单验证
                form.validateFields((errors, values) => {
                    let fromValue = {
                        ...values,
                    }
                    if (!errors) {
                        this.dataSource.splice(this.currentTableIndex,1,{...this.dataSource[this.currentTableIndex],...fromValue} )
                        this[`${visible}`] = false
                    } else {
                        // this.confirmLoading = false
                    }
                })

            },

        },
        created() {
            // 防止表单未注册
            fields.forEach((v) => this.form.getFieldDecorator(v));
            // 当 model 发生改变时，为表单设置值
            this.$watch("model", () => {
                this.model && this.form.setFieldsValue(pick(this.model, fields));
            });
        },
    }
</script>
<style scoped lang="less">
    @basehight: 56px;

    .buttonGray, .buttonGray:hover {
        color: #d9d9d9;
        margin-right: 10px;
        background: #fafafa;
    }

    .t-dr {
        .design-header {
            width: 100%;
            height: @basehight;
            line-height: @basehight;
            border-bottom: 1px solid #e8e8e8;
            background-color: #fff;

            .left-step {
                // width: 70%;
                padding: 0 5% !important;

                .ant-steps {
                    padding-top: 10px;
                }
            }
        }
    }

    /deep/ .ant-drawer-header,
    /deep/ .ant-drawer-body {
        padding: 0 !important;
    }

    .right-btn {
        width: 30%;
        display: flex;
        align-items: center;
        justify-content: flex-end;
        padding-right: 20px;
    }

    /deep/ .bpmn-viewer-container {
        height: calc(100vh - 88px);
    }

    .cancelBtn {
        background: #E4746F !important;
        border-color: #E4746F !important;
        color: #fff;
    }

    .cancelBtn:hover {
        opacity: 0.9;
    }

    /deep/ .ant-drawer-content {
        background-color: #F0F2F5;
    }

    .logo {
        width: 160px;
        padding-left: 45px;
        display: flex;
        align-items: center;
        img {
            width: 32px;
            height: 32px;
        }
        .title {
            font-weight: 500;
            display: inline;
            font-size: 16px;
            padding-left: 10px;
        }
    }

    .design-body {
        height: calc(100vh - 76px);
        margin: 10px;
        background-color: #fff;
    }


</style>
